# -*- coding: utf-8 -*-
# @Author : Yuan
import pickle

import base64
from django_redis import get_redis_connection

from meiduo_mall import settings
from itsdangerous import TimedJSONWebSignatureSerializer
from apps.users.models import User
serializer = TimedJSONWebSignatureSerializer(secret_key=settings.SECRET_KEY, expires_in=3600)


def generate_access_token(open_id):
    access_token = serializer.dumps({'open_id': open_id})
    return access_token.decode()


def check_access_token(access_token):
    try:
        open_id = serializer.loads(access_token)
    except Exception as e:
        return None
    return open_id.get('open_id')


def generate_verify_email_url(user):
    token = serializer.dumps({'user_id': user.id, 'email': user.email})
    verify_url = settings.EMAIL_VERIFY_URL + '?token=' + token.decode()
    return verify_url


def check_verify_email(token):
    try:
        data_dict = serializer.loads(token)
    except Exception as e:
        return None
    else:
        try:
            user_id = data_dict.get('user_id')
            email = data_dict.get('email')
            user = User.objects.get(id=user_id, email=email)
        except User.DoesNotExist:
            return None
        else:
            return user


def merge_carts_cookie_to_redis(request, response):
    """
    合并购物车
    :param request:
    :param response:
    :return:
    """
    user = request.user
    carts = request.COOKIES.get('carts')
    if carts:
        carts = pickle.loads(base64.b64decode(carts.encode()))
    else:
        carts = {}
    carts_redis = {}
    is_selected = []
    is_not_selected = []
    for sku_id, count_selected in carts.items():
        carts_redis[sku_id] = count_selected['count']
        if count_selected['selected']:
            is_selected.append(sku_id)
        else:
            is_not_selected.append(sku_id)

    redis_cli = get_redis_connection('carts')
    redis_pl = redis_cli.pipeline()
    if carts_redis:
        redis_pl.hmset('carts_%s' % user.id, carts_redis)
    if is_selected:
        redis_pl.sadd('selected_%s' % user.id, *is_selected)
    if is_not_selected:
        redis_pl.srem('selected_%s' % user.id, *is_not_selected)
    redis_pl.execute()
    response.delete_cookie('carts')
    return response


